﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

namespace Scrabble.Model
{
    public partial class Game
    {
        private int ScorePlacement(IEnumerable<TileInPlay> setOfPlays)
        {
            var sumOfTiles = setOfPlays.Aggregate(0, (result, play) => result + ScoreTilePlacement(play));
            var factor = setOfPlays.Aggregate(1, (result, play) => result * PremiumScalingAt(play.Location));

            return sumOfTiles * factor;
        }

        private int ScoreTilePlacement(TileInPlay play)
        {
            Contract.Requires<ArgumentNullException>(play != null);

            ScoringStyle scoringStyle;
            _premiumSquares.TryGetValue(play.Location, out scoringStyle);

            var factor =
                scoringStyle == ScoringStyle.DoubleLetter ? 2 :
                scoringStyle == ScoringStyle.TripleLetter ? 3 : 1;

            return play.Tile.Points * factor;
        }

        private int PremiumScalingAt(BoardLocation location)
        {
            Contract.Requires<ArgumentNullException>(location != null);
            Contract.Requires<ArgumentOutOfRangeException>(location.IsWithinBounds);

            ScoringStyle scoringStyle;
            _premiumSquares.TryGetValue(location, out scoringStyle);

            return
                scoringStyle == ScoringStyle.DoubleWord ? 2 :
                scoringStyle == ScoringStyle.TripleWord ? 3 : 1;
        }

    }
}
